package com.lollipop.programming.thread.sequential;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @Author Lollipop
 * @Date 2025/7/28 16:51
 * @Description 多线程顺序执行 - 线程Semaphore Demo
 * @Version 1.0
 */
@Slf4j
public class ThreadSemaphore {
    public static void main(String[] args) {
        Semaphore semB = new Semaphore(0);
        Semaphore semC = new Semaphore(0);

        Thread threadA = new Thread(() -> {
            log.info("任务A开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("任务A执行异常：{}", e.getMessage());
            }
            log.info("任务A执行完成");
            semB.release();
        });

        Thread threadB = new Thread(() -> {
            try {
                semB.acquire();
            } catch (InterruptedException e) {
                log.error("任务B等待异常：{}", e.getMessage());
            }
            log.info("任务B开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("任务B执行异常：{}", e.getMessage());
            }
            log.info("任务B执行完成");
            semC.release();
        });

        Thread threadC = new Thread(() -> {
            try {
                semC.acquire();
            } catch (InterruptedException e) {
                log.error("任务C等待异常：{}", e.getMessage());
            }
            log.info("任务C开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("任务C执行异常：{}", e.getMessage());
            }
            log.info("任务C执行完成");
        });

        threadA.start();
        threadB.start();
        threadC.start();
    }
}
